package com.zz.forum.service.impl;

import com.zz.forum.common.AppResult;
import com.zz.forum.common.ResultCode;
import com.zz.forum.dao.UserMapper;
import com.zz.forum.exception.ApplicationException;
import com.zz.forum.model.User;
import com.zz.forum.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        //1.非空校验
        if(user == null || user.getUsername() == null
                || user.getPassword() == null || user.getNickname() == null) {
            //打印日志
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常,统一返回Application
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //根据用户名查询用户信息
        User existUser = userMapper.selectByUserName(user.getUsername());
        if(existUser != null) {
            //打印日志
            log.error(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        //新增用户，设值
        int insert = userMapper.insert(user);
        //检查是否插入成功
        if(insert != 1) {
            //打印日志
            log.error(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //打印日志
        log.info("用户注册成功，用户名: " + user.getUsername() + ".");

    }
}
